// cloudfunctions/getMyCollections/index.js
const cloud = require('wx-server-sdk');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    const { userId, page = 1, pageSize = 10 } = event;
    
    // 验证参数
    if (!userId) {
      return { success: false, message: '缺少userId参数' };
    }
    
    // 计算分页参数
    const skip = (page - 1) * pageSize;
    
    // 查询我收藏的商品记录
    const collectionsResult = await db.collection('user_collections')
      .where({
        user_id: userId,
      })
      .orderBy('createTime', 'desc')
      .skip(skip)
      .limit(pageSize)
      .get();
    
    // 提取所有goodsId
    const goodsIds = collectionsResult.data.map(item => item.item_id);
    
    // 查询总数量
    const totalResult = await db.collection('user_collections')
      .where({
        user_id: userId,
      })
      .count();
    
    // 如果没有商品ID，直接返回空结果
    if (goodsIds.length === 0) {
      return {
        success: true,
        data: {
          list: [],
          total: totalResult.total
        },
        message: '获取我收藏的商品成功'
      };
    }
    
    // 根据goodsIds批量查询商品信息
    const goodsResult = await db.collection('blindbox_goods')
      .where({
        _id: _.in(goodsIds)
      })
      .get();
    
    // 将商品信息合并到收藏记录中
    const goodsMap = {};
    goodsResult.data.forEach(goods => {
      goodsMap[goods._id] = goods;
    });
    
    const resultList = collectionsResult.data.map(collection => {
      const goods = goodsMap[collection.item_id] || {};
      return {
        ...collection,
        goodsInfo: goods,
        // 提取常用商品信息到外层方便前端使用
        goodsId: goods._id,
        goodsImage: goods.image || '',
        goodsPrice: goods.goodsPrice,
        sellerName: goods.sellerName
      };
    });
    
    return {
      success: true,
      data: {
        list: resultList,
        total: totalResult.total
      },
      message: '获取我收藏的商品成功'
    };
  } catch (error) {
    console.error('获取我收藏的商品失败', error);
    return {
      success: false,
      message: error.message || '服务器错误',
      error: error.message
    };
  }
};